package xyz.ljcc.ccmt.commons.repository.base;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

/*
 * SimpleJpaRepository 包含了部分JPA基本的实现方法
 */

public class BaseRepositoryImpl<T,ID extends Serializable> extends SimpleJpaRepository<T, ID>
	implements BaseRepository<T, ID> {

	private final EntityManager entityManager;
	
	public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
		super(domainClass, em);
		this.entityManager = em;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Object[]> findBySQL(String sql, Object... args) {
		Query query =  entityManager.createNativeQuery(sql); 
		int i = 0;
		for (Object arg : args) {
			query.setParameter(++i, arg);
		}
		return query.getResultList();
	}

	@Override
	public void updateBySql(String sql, Object... args) {
		Query query =  entityManager.createNativeQuery(sql);
		int i = 0;
		for (Object arg : args) {
			query.setParameter(++i, arg);
		}
		query.executeUpdate();
	}

	@Override
	public void updateByHql(String hql, Object... args) {
		Query query = entityManager.createQuery(hql);
		int i = 0;
		for (Object arg : args) {
			query.setParameter(++i, arg);
		}
		query.executeUpdate();
	}
	
	
	
}
